
#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <iostream>
#include <functional>
#include <unordered_map>
#include"Log.hpp"

using namespace LogMudule;
class DictServer
{
public:
    //初始化
    DictServer(uint16_t port)
    :_tcpserver(&_loop,muduo::net::InetAddress("0.0.0.0",port),"dictserver")
    {
        _tcpserver.setConnectionCallback(std::bind(&DictServer::onConnection,this,std::placeholders::_1));
        _tcpserver.setMessageCallback(std::bind(&DictServer::onMessage,this,std::placeholders::_1,
            std::placeholders::_2,std::placeholders::_3));
    }
    
    //开始
    void Start()
    {
        //开始
        _tcpserver.start();

        //循环监视
        _loop.loop();
    }
private:
    //作为回调函数 当建立连接时会触发
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if(conn->connected())
        {
                LOG(LogLevel::DEBUG)<<"连接成功";
        }
        else
        {
                LOG(LogLevel::ERROR)<<"连接失败";
        }
    }


    //作为回调函数，当数据准备就绪时会触发
    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf,muduo::Timestamp t)
    {
        std::string out = buf->retrieveAllAsString();
        if(out.back()=='\n')
        {
            out.pop_back();
        }

        std::string res = handle(out);

        conn->send(res);
    }


    //处理函数
    std::string handle(const std::string &in)
    {
        if(in == "car")
        {
            return "车";
        }
        else
        {
            return "单词不存在";
        }
    }
private:
    //_loop要在_tcpserver前
    muduo::net::EventLoop _loop;
    muduo::net::TcpServer _tcpserver;
};



int main()
{
    DictServer ds(9090);
    ds.Start();
    return 0;
}